package leetcode.editor.cn.util.arr;


import java.util.Arrays;

public class ArrayUtil {
    /**
     * 字符串解析数组
     *
     * @param str
     * @return
     */
    public static Object genArrayByString(String str) {
        str = str.replaceAll("\\s", "");

        // 数组维度
        int level = 0;

        char f = str.charAt(0);

        for (int i = 0; i < 3; i++) {
            if (str.charAt(i) == f) {
                level++;
            } else {
                break;
            }
        }

        switch (level) {
            case 1:
                return gen1ArrayByString(str);
            case 2:
                return gen2ArrayByString(str);
            case 3:
                return gen3ArrayByString(str);
            default:
                return null;
        }
    }

    private static int[] gen1ArrayByString(String str) {
        return Arrays.stream(str.substring(1, str.length() - 1).split(",")).mapToInt(e -> Integer.parseInt(e.trim())).toArray();
    }


    private static int[][] gen2ArrayByString(String str) {
        str = str.substring(2, str.length() - 2);
        String[] split = str.split("],\\[");

        int[][] arr = new int[split.length][];
        for (int i = 0, splitLength = split.length; i < splitLength; i++) {
            arr[i] = Arrays.stream(split[i].split(",")).mapToInt(e -> Integer.parseInt(e.trim())).toArray();
        }
        return arr;
    }

    private static int[][][] gen3ArrayByString(String str) {
        str = str.substring(3, str.length() - 3);
        String[] split = str.split("]],\\[\\[");

        int[][][] arr = new int[split.length][][];
        for (int i = 0, splitLength = split.length; i < splitLength; i++) {
            arr[i] = gen2ArrayByString("[[" + split[i] + "]]");
        }
        return arr;
    }

    public static void main(String[] args) {
//        System.out.println(Arrays.toString((int[]) genArrayByString("[11,21,41]")));
//        int[][] arr = (int[][]) genArrayByString("[[5,6],[0,2],[1,7],[5,9],[1,8],[3,4],[0,6],[0,7],[0,3],[8,9]]");
//        for (int[] ints : arr) {
//            System.out.println(Arrays.toString(ints));
//        }
        int[][][] arr2 = (int[][][]) genArrayByString("[[[ 0,  1,  2], [ 3,  4,  5]], [[ 6,  7,  8], [ 9, 10, 11]]]");
        for (int[][] ints : arr2) {
            for (int[] s : ints) {
                System.out.print(Arrays.toString(s));
            }
            System.out.println();
        }
    }
}
